// pages/parkPayment/parkPayment.js
const app = getApp()
var request = require("../../utils/request.js");
import Toast from '../../miniprogram_npm/@vant/weapp/toast/toast';
Page({
  /**
   * 页面的初始数据
   */
  data: {
    statusBarHeight: app.globalData.statusBarHeight,
    tabs: [{
      id: 0,
      name: '普通车辆',
      select: true
    },
    {
      id: 1,
      name: '新能源',
      select: false
    },

    ],
    inputLen: 7,
    isFocus: true,
    carNo: '',
    translateSpace: 0,
    inputType: 1, // 车牌输入类型，1简称，2数字或者字母,
    showPlateInput: false,
    showBindPhone: false,
    hasPhone: false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let that = this;
    let opendId = wx.getStorageSync('opneId');
    let userId = wx.getStorageSync('userId');
    if (userId != undefined && userId != '') {
      that.getUserInfo(userId);
      that.setData({
        userId: userId
      })
    }
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },
  /**
   * 切换tab
   */
  selectTab(e) {
    let index = e.target.dataset.index;
    let that = this;
    let tabs = that.data.tabs;
    if (index == 0) {
      that.setData({
        inputLen: 7
      })
    } else {
      that.setData({
        inputLen: 8
      })
    }
    for (let i = 0; i < tabs.length; i++) {
      if (i == index) {
        tabs[i].select = true
      } else {
        tabs[i].select = false;
      }
    }
    that.setData({
      tabs: tabs
    })
  },
  /**
   * 输入车牌号
   * @param {*} e 
   */
  onFocus: function (e) {
    var that = this;
    let regExp = /^[\u4e00-\u9fa5]+/;
    let inputType = 1;
    if (regExp.test(that.data.carNo)) {
      inputType = 2;
    }
    that.setData({
      showPlateInput: true,
      inputType: inputType
    });
  },
  /**
   * 设置input值
   * @param {*} e 
   */
  setValue: function (e) {
    var that = this;
    that.setData({
      iptValue: e.detail.value
    });
  },
  /**
   * 自定义键盘点击
   */
  inputChange(e) {
    let that = this;
    let iptValue = that.data.iptValue;
    let value = e.detail;
    let keyBoardType = that.data.keyBoardType;
    that.setData({
      iptValue: iptValue + value
    })
    if (keyBoardType == 1) {
      that.setData({
        keyBoardType: 2
      })
    }
  },
  /**
   * 用于点击弹出键盘输入，space为键盘弹出后向上拉取的距离 
   * @param {*} e 
   */
  handleClick(e) {
    /* 150为键盘的高度 */
    let space = -(e.currentTarget.offsetTop - 150);
    /* regExp用于判断当前已输入的车牌号是否是中文，并让键盘显示中文还是英文输入 */
    let regExp = /^[\u4e00-\u9fa5]+/;
    let inputType = 1;
    if (regExp.test(this.data.carNo)) {
      inputType = 2;
    }

    this.setData({
      translateSpace: space,
      showPlateInput: true,
      inputType
    })
  },
  /**
   * 键盘输入操作
   * @param {*} e 
   */
  handlePlateChange(e) {
    let value = e.detail.value;
    let inputLen = this.data.inputLen;
    let type = e.detail.type;
    let carNo = this.data.carNo;
    if (carNo.length < inputLen) {
      carNo += value;
    }
    if (type == 1) {
      this.setData({
        inputType: 2
      })
    }
    this.setData({
      carNo
    })
  },
  /**
   * 点击键盘上的确定
   */
  handlePlateConfirm() {
    /* isCarPlate用于判断输入的车牌号是否符合规范 */
    if (!this.isCarPlate(this.data.carNo)) {
      wx.showToast({
        title: '请输入正确的车牌号',
        icon: 'none',
        duration: 2000
      })
      return false;
    }
    this.setData({
      translateSpace: 0,
      showPlateInput: false,
      inputType: 1
    })
  },
  /**
   * 用于键盘输入删除
   * @param {*} e 
   */
  handlePlateDelete(e) {
    let carNo = this.data.carNo;
    carNo = carNo.substring(0, carNo.length - 1);
    if (carNo.length == 0) {
      this.setData({
        inputType: 1
      })
    }
    this.setData({
      carNo,
    })
  },
  /**
   * 判断车牌号
   * @param {String} value 车牌号
   */
  isCarPlate(value) {
    return /^(([京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领][A-Z](([0-9]{5}[DF])|([DF]([A-HJ-NP-Z0-9])[0-9]{4})))|([京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领][A-Z][A-HJ-NP-Z0-9]{4}[A-HJ-NP-Z0-9挂学警港澳使领]))$/.test(value);
  },
  /**
   * 授权
   * @param {*} e 
   */
  bindGetUserInfo: function (e) {
    let that = this;
    let userInfo = e.detail.userInfo;
    that.setData({
      userInfo: userInfo
    })
    if (userInfo) {
      wx.login({
        success: res => {
          that.getOpenId(res.code);
        }
      });
    }
  },
  /**
   * 获取opendId
   */
  getOpenId(code) {
    let that = this;
    let info = that.data.userInfo;
    let userInfo = {
      headUrl: info.avatarUrl,
      nickName: info.nickName,
      sex: info.gender,
    }
    let url = "/api/pay/getOpenId?code=" + code;
    var params = userInfo;
    request.http(url, 'POST', params)
      .then((res) => {
        if (res.data.code == 200) {
          let openId = res.data.data.openId;
          let userId = res.data.data.userId;
          let session_key = res.data.data.session_key;
          wx.setStorageSync('sessionKey', session_key);
          wx.setStorageSync('openId', openId);
          wx.setStorageSync('userId', userId);
          //获取用户信息
          that.getUserInfo(userId);
          that.setData({
            openId: openId,
            userId: userId
          })
        } else {
          Toast.fail('获取失败');
        }
      })
      .catch((errMsg) => {
        // wx.showToast({
        //   title: '获取失败',
        //   icon: 'loading',
        //   duration: 1000,
        // })
      });
  },
  /**
   * 跳转到订单详情页
   */
  toOrderInfo() {
    let that = this;
    let carCardNum = that.data.carNo;
    if (carCardNum == undefined && carCardNum == '') {
      Toast('请输入手机号');
      return
    }
    that.setData({
      showPlateInput: false
    })
    wx.navigateTo({
      url: '../payForm/payForm?carCardNum=' + carCardNum,
    })
  },
  /**
   * 回到首页
   */
  toIndex() {
    wx.navigateTo({
      url: '../index/index',
    })
  },
  /**
   * 展示提示绑定手机号的弹窗
   */
  showBindPhone() {
    this.setData({
      showBindPhone: true
    })
  },
  /**
   * 关闭提示绑定手机号的弹窗
   */
  closeBindPop() {
    this.setData({
      showBindPhone: false
    })
  },
  /**
   * 获取手机号
   * @param {*} e 
   */
  getPhoneNumber: function (e) {
    var that = this;
    if (e.detail.errMsg == "getPhoneNumber:ok") {
      let encryptedData = e.detail.encryptedData;
      let iv = e.detail.iv;
      that.setData({
        encryptedData: encryptedData,
        iv: iv
      })
      wx.login({
        success: res => {
          if (res.code) {
            let code = res.code;
            wx.checkSession({
              success: function (res) {
                var sessionKey = wx.getStorageSync('sessionKey');
                var userId = wx.getStorageSync('userId');
                let url = "/api/cUser/updateMobilePhone?iv=" + iv + "&encryptedData=" + encryptedData + "&userId=" + userId + "&code=" + code;
                request.http(url, 'POST')
                  .then((res) => {
                    if (res.data.code == 200) {
                      Toast.success('绑定成功');
                      let userId = wx.getStorageSync('userId');
                      that.getUserInfo(userId);
                      that.closeBindPop();
                    } else {
                      Toast.fail('绑定失败');
                      wx.login({
                        success: res => {
                          if (res.code) {
                            that.getOpenId(res.code);
                          }
                        }
                      })
                    }
                  })
              },
              fail: function (res) {
                wx.login({
                  success: res => {
                    if (res.code) {
                      that.getOpenId(res.code);
                    }
                  }
                })
              }
            })
          }
        }
      })
    }
  },
  /**
   * 获取用户信息
   * @param {*} userId 用户ID
   */
  getUserInfo(userId) {
    let that = this;
    let url = "/api/cUser/myInfo?userId=" + userId;
    request.http(url, 'POST')
      .then((res) => {
        if (res.data.code == 200) {
          let user = res.data.data.user;
          if (user != undefined && user != null) {
            if (user.mobilePhone == null || user.mobilePhone == undefined || user.mobilePhone == '') {
              that.setData({
                showBindPhone: true
              })
            } else {
              that.setData({
                showBindPhone: false
              })
            }
          }
        } else {
          Toast.fail('网络错误');
        }
      })
  },
})